<?php
/**
 * 后四个菜单的功能
 * edit by yjmp
*/
define('IN_ECS', true);
define('ECS_ADMIN', true);

require(dirname(__FILE__) . '/includes/init.php');
require(ROOT_PATH . 'includes/lib_order.php');
require(ROOT_PATH . 'myplug/includes/lib_newfunction.php');
if ($_SESSION['user_id']) {
    $smarty->assign('user_id',$_SESSION['user_id']);
}
if ($_SESSION['user_id'] && $_SESSION['end_time'] != -1 && $_SESSION['end_time'] < time()) {
   $user->logout();
    $Loaction = 'index.php';
    die(ecs_header("Location: $Loaction\n"));
}

$act=$_REQUEST['act'] ? $_REQUEST['act']:'idx';

if ($act == 'idx' || $act == 'edit_profile') 
{
    if ($_SESSION['user_id']) 
    {
        $user_info =  $GLOBALS['db']->getRow('SELECT user_name, email, display_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = '.$_SESSION['user_id']);
        $smarty->assign('user_name',$user_info['user_name']);
        $smarty->assign('display_name',$user_info['display_name']);
        $smarty->assign('email',$user_info['email']);
    }
    $smarty->assign('act',$act);
    $smarty->display('idx.html');
}   

//改SESSION的生存周期
if ($act == 'session_out') 
{
    include_once('includes/cls_json.php');
    $session_out = $_POST['session_out'];
    $json = new JSON;
    $result = array(
        'content'=>'修改成功'
        );
    if ($session_out != -1) {
        $_SESSION['end_time'] = $session_out * 6 + time();
    }else
    {
        $_SESSION['end_time'] = -1;
    }
    $result['content'] = $smarty->fetch('library/change_session.lbi');
    $result['msg'] = '修改成功';
    die(json_encode($result));
}


//修改个人资料
if ($act == 'update_profile') 
{
    include_once('includes/cls_json.php');
    $json = new JSON;
    $result = array(
        'error'=>1,
        'message'=>''
        );
    
    //数据获取
    $usr = isset($_POST['user_name'])? $_POST['user_name'] : '';
    $email = isset($_POST['email'])? $_POST['email'] : '';
    $old_pwd = isset($_POST['old_pwd'])? $_POST['old_pwd'] : '';
    $pwd = isset($_POST['pwd'])? $_POST['pwd'] : '';
    $cfm_pwd = isset($_POST['cfm_pwd'])? $_POST['cfm_pwd'] : '';
    $result['content'] = $cfm_pwd;
    $user_id = $_SESSION['user_id'];

    //数据验证
    if ($pwd != $cfm_pwd && $pwd && $cfm_pwd && $old_pwd) 
    {
    	$result['message'] = '两次密码输入不一致';
    	die($json->encode($result));
    }

    //数据修改
    $user_info = $user->get_profile_by_id($user_id); 
    
    //修改密码
    if ($pwd && $old_pwd && $cfm_pwd) 
    {
        if ($user->check_user($_SESSION['user_name'], $old_pwd))
        { 
            if ($user->edit_user(array('username'=> (empty($code) ? $_SESSION['user_name'] : $user_info['user_name']), 'old_password'=>$old_pwd, 'password'=>$pwd), empty($code) ? 0 : 1))
            {
                $sql="UPDATE ".$ecs->table('users'). "SET `ec_salt`='0' WHERE user_id= '".$user_id."'";
                $db->query($sql);
                //修改完成
                $result['message'] = '修改完成';
                $result['error'] = '0';
                //$result['content'] = $smarty-> $smarty->fetch('library/profile.lbi');
            }
            else
            {
                //修改失败
                $result['message'] = '修改失败';
                $result['error'] = '1';
            }
        }
        else
        {
            $result['message'] = '密码错误';
            $result['error'] = '1';
        }
    }
    
    //修改个人数据
    if (($usr || $email) && $old_pwd == '') 
    {
        $GLOBALS['db']->query(' UPDATE '.$GLOBALS['ecs']->table('users').' SET display_name = "'.$usr.'" ,email = "'.$email.'" WHERE user_id = '.$user_id.'');
        $result['message'] = '修改完成';
        $result['error'] = '0';
    }
    
    die(json_encode($result));
    
}


//数据导出成其他格式
if ($act == 'exprot_excel') 
{
    // 引入phpexcel核心类文件
    require_once ROOT_PATH . 'includes/phpexcel/Classes/PHPExcel.php';
    // 实例化excel类
    $objPHPExcel = new PHPExcel();
    // 操作第一个工作表
    $objPHPExcel->setActiveSheetIndex(0);
    // 设置sheet名
    $objPHPExcel->getActiveSheet()->setTitle('cash_drawer_record');

    // 设置表格宽度
    $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);

    // 列名表头文字加粗
    $objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getFont()->setBold(true);
    // 列表头文字居中
    $objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getAlignment()
        ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

    $objPHPExcel->getActiveSheet()->setCellValue('A1', '时间');
    $objPHPExcel->getActiveSheet()->setCellValue('B1', '收入');
    $objPHPExcel->getActiveSheet()->setCellValue('C1', '支出');
    $objPHPExcel->getActiveSheet()->setCellValue('D1', '余额');
    $objPHPExcel->getActiveSheet()->setCellValue('E1', '订单号');
    $objPHPExcel->getActiveSheet()->setCellValue('F1', '操作人');
    $objPHPExcel->getActiveSheet()->setCellValue('G1', '地址');
    $objPHPExcel->getActiveSheet()->setCellValue('H1', '备注');

    // 数据起始行
    $row_num = 2;

    //数据源
    $cash_drawer =get_cash_drawer();

    // 向每行单元格插入数据
    foreach ($cash_drawer as $value) 
    {
        // 设置所有垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('A' . $row_num . ':' . 'H' . $row_num)->getAlignment()
            ->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        // 居中
        $objPHPExcel->getActiveSheet()->getStyle('A' . $row_num . ':' . 'H' . $row_num)->getAlignment()
            ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        // 设置单元格数值
        $objPHPExcel->getActiveSheet()->setCellValue('A' . $row_num, $value['add_time']);
        $objPHPExcel->getActiveSheet()->setCellValue('B' . $row_num, $value['in_come']);
        $objPHPExcel->getActiveSheet()->setCellValue('C' . $row_num, $value['out_come']);
        $objPHPExcel->getActiveSheet()->setCellValue('D' . $row_num, $value['balance']);
        $objPHPExcel->getActiveSheet()->setCellValue('E' . $row_num, $value['order_id']);
        $objPHPExcel->getActiveSheet()->setCellValue('F' . $row_num, $value['cashier']);
        $objPHPExcel->getActiveSheet()->setCellValue('G' . $row_num, $value['location']);
        $objPHPExcel->getActiveSheet()->setCellValue('H' . $row_num, $value['note']);
        $row_num++;
    }
    $outputFileName = 'balance_' . time() . '.xls';
    $xlsWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header('Content-Disposition:inline;filename="' . $outputFileName . '"');
    header("Content-Transfer-Encoding: binary");
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Pragma: no-cache");
    $xlsWriter->save("php://output");
    echo file_get_contents($outputFileName);
}   

//日总结的excel导出
if ($act == 'end_day_execl') {
    // 引入phpexcel核心类文件
    require_once ROOT_PATH . 'includes/phpexcel/Classes/PHPExcel.php';
    // 实例化excel类
    $objPHPExcel = new PHPExcel();
    // 操作第一个工作表
    $objPHPExcel->setActiveSheetIndex(0);
    // 设置sheet名
    $objPHPExcel->getActiveSheet()->setTitle('cash_drawer_record');

    // 设置表格宽度
    $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
    $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);

    // 列名表头文字加粗
    $objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getFont()->setBold(true);
    // 列表头文字居中
    $objPHPExcel->getActiveSheet()->getStyle('A1:H1')->getAlignment()
        ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

    $objPHPExcel->getActiveSheet()->setCellValue('A1', '订单号');
    $objPHPExcel->getActiveSheet()->setCellValue('B1', '出纳');
    $objPHPExcel->getActiveSheet()->setCellValue('C1', '店铺');
    $objPHPExcel->getActiveSheet()->setCellValue('D1', '钱箱');
    $objPHPExcel->getActiveSheet()->setCellValue('E1', '客户名');
    $objPHPExcel->getActiveSheet()->setCellValue('F1', '总计');
    $objPHPExcel->getActiveSheet()->setCellValue('G1', '日期');
    $objPHPExcel->getActiveSheet()->setCellValue('H1', '状态');

    // 数据起始行
    $row_num = 2;

    //数据源
    $user_id  = $_SESSION['user_id'];
    $cashier  = $GLOBALS['db']->getOne('SELECT user_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$user_id.'"'); 
    $time = date("Y-m-d",time());
    $start_time_stamp = strtotime($time.'00:00:00');
    $end_time_stamp = strtotime($time.'23:59:59');
    $order_list = $GLOBALS['db']->getAll(' SELECT * FROM '.$GLOBALS['ecs']->table('order_info').' WHERE ywid = '.$user_id.' AND add_time > '.$start_time_stamp.' AND add_time < '.$end_time_stamp.'');
    if ($order_list) {
        foreach ($order_list as $key => $value) {
            $order_list[$key]['cashier'] = $GLOBALS['db']->getOne(' SELECT user_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$value['ywid'].'"');
            $order_list[$key]['add_date'] = date("Y-m-d H:i:s",$value['add_time']);
            $order_list[$key]['customer'] = $GLOBALS['db']->getOne(' SELECT user_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$value['user_id'].'"');
            $order_list[$key]['amount_format'] = price_format($value['order_amount'],false); 
        }
    }
    // 向每行单元格插入数据
    foreach ($order_list as $value) 
    {
        // 设置所有垂直居中
        $objPHPExcel->getActiveSheet()->getStyle('A' . $row_num . ':' . 'H' . $row_num)->getAlignment()
            ->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
        // 居中
        $objPHPExcel->getActiveSheet()->getStyle('A' . $row_num . ':' . 'H' . $row_num)->getAlignment()
            ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

        // 设置单元格数值
        $objPHPExcel->getActiveSheet()->setCellValue('A' . $row_num, $value['order_id']);
        $objPHPExcel->getActiveSheet()->setCellValue('B' . $row_num, $value['cashier']);
        $objPHPExcel->getActiveSheet()->setCellValue('C' . $row_num, '默认店铺');
        $objPHPExcel->getActiveSheet()->setCellValue('D' . $row_num, '默认钱箱');
        $objPHPExcel->getActiveSheet()->setCellValue('E' . $row_num, $value['customer']);
        $objPHPExcel->getActiveSheet()->setCellValue('F' . $row_num, $value['amount_format']);
        $objPHPExcel->getActiveSheet()->setCellValue('G' . $row_num, $value['add_date']);
        $status = '';
        switch($value['order_status']){
            case 0:
            $status = '未确认';
            break;
            case 1:
            $status = '确认';
            break;
            case 2:
            $status = '取消';
            break;
            case 4:
            $status = '退货';
            break;
            case 5:
            $status = '已发货';
            break;
            default:
            break;
            }
        $objPHPExcel->getActiveSheet()->setCellValue('H' . $row_num, $status);
        $row_num++;
    }
    $outputFileName = 'daily_report_' . time() . '.xls';
    $xlsWriter = new PHPExcel_Writer_Excel5($objPHPExcel);
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header('Content-Disposition:inline;filename="' . $outputFileName . '"');
    header("Content-Transfer-Encoding: binary");
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Pragma: no-cache");
    $xlsWriter->save("php://output");
    echo file_get_contents($outputFileName);
}

//日总结CSV导出
if ($act == 'end_day_csv') {
    //表头
    $str = "订单号,出纳,店铺,钱箱,客户名,日期,总计,状态\n";
    //数据源
    $user_id  = $_SESSION['user_id'];
    $cashier  = $GLOBALS['db']->getOne('SELECT user_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$user_id.'"'); 
    $time = date("Y-m-d",time());
    $start_time_stamp = strtotime($time.'00:00:00');
    $end_time_stamp = strtotime($time.'23:59:59');
    $order_list = $GLOBALS['db']->getAll(' SELECT * FROM '.$GLOBALS['ecs']->table('order_info').' WHERE ywid = '.$user_id.' AND add_time > '.$start_time_stamp.' AND add_time < '.$end_time_stamp.'');
    if ($order_list) {
        foreach ($order_list as $key => $value) {
            $date = date("Y-m-d H:i:s",$value['add_time']);
            $customer = $GLOBALS['db']->getOne(' SELECT user_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$value['user_id'].'"');
            $status = '';
            switch($value['order_status']){
            case 0:
            $status = '未确认';
            break;
            case 1:
            $status = '确认';
            break;
            case 2:
            $status = '取消';
            break;
            case 4:
            $status = '退货';
            break;
            case 5:
            $status = '已发货';
            }
            $amount = price_format($value['order_amount'],false);
            $str.=$value['order_id'].",".$cashier.",默认店铺,默认钱箱,".$customer.",".$date.",".$amount.",".$status."\n"; 
        }
    }

    $filename = date('Ymd').'_每日报告.csv'; //设置文件名   
    export_csv($filename,$str); //导出   
}

//日总结word导出
if ($act == 'end_day_word') {
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
    $wordStr = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:doc' xmlns='http://www.w3.org/TR/REC-html40'><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>";
    //内容
    $wordStr .= "<tr><th>订单号</th><th>出纳</th><th>店铺</th><th>钱箱</th><th>客户名</th><th>日期</th><th>总计</th><th>状态</th></tr>";
     $user_id  = $_SESSION['user_id'];
    $cashier  = $GLOBALS['db']->getOne('SELECT user_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$user_id.'"'); 
    $time = date("Y-m-d",time());
    $start_time_stamp = strtotime($time.'00:00:00');
    $end_time_stamp = strtotime($time.'23:59:59');
    $order_list = $GLOBALS['db']->getAll(' SELECT * FROM '.$GLOBALS['ecs']->table('order_info').' WHERE ywid = '.$user_id.' AND add_time > '.$start_time_stamp.' AND add_time < '.$end_time_stamp.'');
    if ($order_list) {
        foreach ($order_list as $key => $value) {
            $date = date("Y-m-d H:i:s",$value['add_time']);
            $customer = $GLOBALS['db']->getOne(' SELECT user_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$value['user_id'].'"');
            $status = '';
            switch($value['order_status']){
            case 0:
            $status = '未确认';
            break;
            case 1:
            $status = '确认';
            break;
            case 2:
            $status = '取消';
            break;
            case 4:
            $status = '退货';
            break;
            case 5:
            $status = '已发货';
            }
            $amount = price_format($value['order_amount'],false);
            $str.=$value['order_id'].",".$cashier.",默认店铺,默认钱箱,".$customer.",".$date.",".$amount.",".$status."\n"; 
            $wordStr.='<tr><td>'.$value['order_id'].'</td><td>'.$cashier.'</td><td>默认店铺</td><td>默认钱箱</td><td>'.$customer.'</td><td>'.$date.'</td><td>'.$amount.'</td><td>'.$status.'</td></tr>';
        }
    }
    $wordStr .= '</table></body></html>';
    //防止导出乱码
    $wordStr = iconv("utf-8", "GBK", $wordStr);
    header("Content-Type: application/doc");
    header("Content-Disposition: attachment; filename=" . 'daily_reoprt' . ".doc");
    echo $wordStr;
}

//钱箱显示方法
if ($act == 'cash_drawer') 
{
	$user_id = $_SESSION['user_id'];
    $crt_balance =  $GLOBALS['db']->getOne('SELECT crt_balance FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$user_id.'"');
    $cash_drawer = get_cash_drawer();

    $smarty->assign('crt_balance',$crt_balance);
    $smarty->assign('cash_drawer', $cash_drawer);
    $smarty->assign('act', $act);
    $smarty->display('idx.html');
}

//钱箱增加数据
if ($act == 'add_cash_drawer') 
{
    //数据获取
    $amount = $_POST['amount'];
    $type  = $_POST['type'];
    $note = $_POST['note'];
    $user_id = $_SESSION['user_id'];
    
    //原来的余额
    $balance_org = $GLOBALS['db']->getOne('SELECT crt_balance FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$user_id.'"');

    $order_id = '自定义订单';
    $cashier = $GLOBALS['db']->getOne('SELECT user_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$user_id.'"');
    $location_id = $GLOBALS['db']->getOne('SELECT location_id FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$user_id.'"');
    $location = '';
    if ($location_id) {
        $location = $GLOBALS['db']->getOne('SELECT location_name FROM '.$GLOBALS['ecs']->table('webpos_location').' WHERE location_id = "'.$location_id.'"');
    }
    $add_time = time();

    $op = 0;
    if ($type) {
        $op = 1;
    }else
    {
        $op = -1;
    }
    $balance = $balance_org + $amount * $op;
    $in = $op > 0 ? $amount : 0;
    $out = $op < 0 ? $amount : 0;

    $sql = ' INSERT INTO '.$GLOBALS['ecs']->table('cash_drawer').' ( user_id, in_come , out_come , balance , order_id , cashier , location , note , add_time ) VALUES ( '.$user_id.', "'.$in.'", "'.$out.'", "'.$balance.'", "'.$order_id.'", "'.$cashier.'", "'.$location.'", "'.$note.'", "'.$add_time.'" ) ';
    $GLOBALS['db']->query($sql);
    $GLOBALS['db']->query(' UPDATE '.$GLOBALS['ecs']->table('users').' SET crt_balance = "'.$balance.'" WHERE user_id = "'.$_SESSION['user_id'].'"');

    include_once('includes/cls_json.php');
    $json = new JSON;
    $result = array(
        'content'=>''
        );

    $cash_drawer = get_cash_drawer();

    $crt_balance =  $GLOBALS['db']->getOne('SELECT crt_balance FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$user_id.'"');
    
    $smarty->assign('cash_drawer',$cash_drawer);
    $smarty->assign('crt_balance',$crt_balance);
    $content = $smarty->fetch('library/cash_drawer.lbi');
    $result['content'] = $content;
    die(json_encode($result));
}

//钱箱导出csv
if ($act == 'cash_drawer_csv') {
    //表头
    $str = "时间,收入,支出,余额,订单编号,操作人,位置,备注\n"; 
    $cash_drawer = get_cash_drawer();
    foreach ($cash_drawer as $k => $v) {
        $add_time =  $v['add_time'];
        $in_come = $v['in_come'];
        $out_come =$v['out_come'];
        $balance =$v['balance'];
        $cashier = $v['cashier'];
        $location = $v['location'];
        $note = $v['note'];
        $str.=$add_time.",".$in_come.",".$out_come.",".$balance.",".$v['order_id'].",".$cashier.",".$location.",".$note."\n";
    }
    $filename = date('Ymd').'_钱箱.csv'; //设置文件名   
    export_csv($filename,$str); //导出   
}

//钱箱导出word文件 
if ($act == 'cash_drawer_word') {
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");
    $wordStr = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:doc' xmlns='http://www.w3.org/TR/REC-html40'><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>";
    //内容
    $wordStr .= "<tr><th>时间</th><th>收入</th><th>支出</th><th>余额</th><th>订单编号</th><th>操作人</th><th>位置</th><th>备注</th></tr>";
    $cash_drawer = get_cash_drawer();
    foreach ($cash_drawer as $k => $v) {
        $wordStr.="<tr><td>".$v['add_time']."</td><td>".$v['in_come']."</td><td>".$v['out_come']."</td><td>".$v['balance']."</td><td>".$v['order_id']."</td><td>".$v['cashier']."</td><td>".$v['location']."</td><td>".$v['note']."</td></tr>";
    }
    $wordStr .= '</table></body></html>';
    //防止导出乱码
    $wordStr = iconv("utf-8", "GBK", $wordStr);
    header("Content-Type: application/doc");
    header("Content-Disposition: attachment; filename=" . 'cash_drawer' . ".doc");
    echo $wordStr;
}

//cart内数据放入on hold orders
if ($act == 'add_to_hold') 
{
    $note = $_POST['note'];

    include_once('includes/cls_json.php');
    $json = new JSON;
    $result = array(
        'hold'=>'',
        'cart'=>''
        );
    /*hold*/
    $cart_info = $GLOBALS['db']->getAll(' SELECT * FROM '.$GLOBALS['ecs']->table('cart').' WHERE user_id = '.$_SESSION['user_id']);
    $add_time  = time();
    foreach ($cart_info as $key => $value) {
        $GLOBALS['db']->query(' INSERT INTO '.$GLOBALS['ecs']->table('on_hold_order').' ( user_id, goods_id, goods_sn, product_id, goods_name, market_price, goods_price, goods_number, goods_attr, is_real, extension_code, parent_id, rec_type, is_gift, is_shipping, can_handsel, goods_attr_id, add_time, note, session_id ) VALUES ( '.$value['user_id'].', '.$value['goods_id'].', "'.$value['goods_sn'].'", '.$value['product_id'].', "'.$value['goods_name'].'", '.$value['market_price'].', '.$value['goods_price'].','.$value['goods_number'].', "'.$value['goods_attr'].'", '.$value['is_real'].', "'.$value['extension_code'].'", '.$value['parent_id'].', '.$value['rec_type'].', '.$value['is_gift'].', '.$value['is_shipping'].', '.$value['can_handsel'].', "'.$value['goods_attr_id'].'", "'.$add_time.'", "'.$note.'", "'.$value['session_id'].'" )');
    }
    /*购物车*/
    clear_cart();        
    $result['cart'] = $smarty->fetch('library/cart_goods.lbi');
    $result['data'] = get_on_hold_info();
    $smarty->assign('on_hold_order', get_on_hold_info());
    $result['hold'] = $smarty->fetch('library/on_hold_order.lbi');
    die(json_encode($result));
}

//on hold order 数据放回cart
if ($act == 'reload_cart') {
    $time = $_POST['time'];

    include_once('includes/cls_json.php');
    $json = new JSON;
    $result = array(
        'hold'=>'',
        'cart'=>''
        );
    $on_hold_orders = $GLOBALS['db']->getAll(' SELECT * FROM '.$GLOBALS['ecs']->table('on_hold_order').' WHERE user_id = '.$_SESSION['user_id'].' AND add_time = '.$time);

    //加入购物车
    foreach ($on_hold_orders as $key => $value) {
         $GLOBALS['db']->query(' INSERT INTO '.$GLOBALS['ecs']->table('cart').' ( user_id, goods_id, goods_sn, product_id, goods_name, market_price, goods_price, goods_number, goods_attr, is_real, extension_code, parent_id, rec_type, is_gift, is_shipping, can_handsel, goods_attr_id, session_id ) VALUES ( '.$value['user_id'].', '.$value['goods_id'].', "'.$value['goods_sn'].'", '.$value['product_id'].', "'.$value['goods_name'].'", '.$value['market_price'].', '.$value['goods_price'].','.$value['goods_number'].', "'.$value['goods_attr'].'", '.$value['is_real'].', "'.$value['extension_code'].'", '.$value['parent_id'].', '.$value['rec_type'].', '.$value['is_gift'].', '.$value['is_shipping'].', '.$value['can_handsel'].', "'.$value['goods_attr_id'].'", "'.$value['session_id'].'" )');
    }
    //删除hold order数据
    $GLOBALS['db']->query(' DELETE FROM '.$GLOBALS['ecs']->table('on_hold_order').' WHERE user_id = '.$_SESSION['user_id'].' AND add_time = '.$time);
    //购物车显示相关
    $cartgoods = get_cart_goods();      
    $smarty->assign('cartgoods',              $cartgoods['goods_list']);
    $smarty->assign('zongji',              $cartgoods['total']);
    $sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id']."";
    $cnum = $db->getOne($sql);
    $result['cnum'] = $cnum;
    $result['zongji'] = $cartgoods['total']['goods_amount'];
    $result['cart'] = $smarty->fetch('library/cart_goods.lbi');

    //hold order 显示相关
    $smarty->assign('on_hold_order', get_on_hold_info());
    $result['hold'] = $smarty->fetch('library/on_hold_order.lbi');

    die(json_encode($result));
}
//on hold order 数据删除
if ($act == 'delete_hold') {
    $time = $_POST['time'];

    include_once('includes/cls_json.php');
    $json = new JSON;
    $result = array(
        'hold'=>'',
        'cart'=>''
        );
    $on_hold_orders = $GLOBALS['db']->getAll(' SELECT * FROM '.$GLOBALS['ecs']->table('on_hold_order').' WHERE user_id = '.$_SESSION['user_id'].' AND add_time = '.$time);
    //删除hold order数据
    $GLOBALS['db']->query(' DELETE FROM '.$GLOBALS['ecs']->table('on_hold_order').' WHERE user_id = '.$_SESSION['user_id'].' AND add_time = '.$time);
    $cartgoods = get_cart_goods();      
    $smarty->assign('cartgoods',              $cartgoods['goods_list']);
    $smarty->assign('zongji',              $cartgoods['total']);
    $sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id']."";
    $cnum = $db->getOne($sql);
    $result['cnum'] = $cnum;
    $result['zongji'] = $cartgoods['total']['goods_amount'];
    $result['cart'] = $smarty->fetch('library/cart_goods.lbi');

    //hold order 显示相关
    $smarty->assign('on_hold_order', get_on_hold_info());
    $result['hold'] = $smarty->fetch('library/on_hold_order.lbi');

    die(json_encode($result));
}
//显示细节
if ($act == 'detail_hold') {
    $time = $_POST['time_stamp'];
    include_once('includes/cls_json.php');
    $json = new JSON;
    $result = array(
        'content'=>''
        );
    $on_hold_order_info = $GLOBALS['db']->getAll(' SELECT * FROM '.$GLOBALS['ecs']->table('on_hold_order').' WHERE add_time = "'.$time.'"');
    $amount = 0;
    foreach ($on_hold_order_info as $k => $v) {
        $amount += $v['goods_price'] * $v['goods_number'];
        $price =  $v['goods_price'] * $v['goods_number'];
        $on_hold_order_info[$key]['total'] = price_format($price,false);
        $on_hold_order_info[$key]['market_price_format'] = price_format($v['market_price'],false);
        $on_hold_order_info[$key]['goods_price_format'] = price_format($v['goods_price'],false);
    }
    $add_date = date('Y-m-d h:i:s',$time);
    $server = $GLOBALS['db']->getOne('SELECT user_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$_SESSION['user_id'].'"');
    $amount = price_format($amount,false);
    $smarty->assign('goods_list',$on_hold_order_info);
    $smarty->assign('amount',$amount);
    $smarty->assign('add_date',$add_date);
    $smarty->assign('server',$server);
    $result['content'] = $smarty->fetch('library/hole_order_detail.lbi');
    die(json_encode($result));
}

//获取x或z类型的报告数据 
if ($act == 'get_x_report') {
    include_once('includes/cls_json.php');
    $json = new JSON;
    $result = array(
        'content'=>'',
        'msg'=>''
        );
    $user_id  = $_SESSION['user_id'];
    /*获取数据*/
    //出纳
    $cashier = $GLOBALS['db']->getOne('SELECT user_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$user_id.'"');
    //用于计算的时间戳
    $time = date("Y-m-d",time());
    $start_time_stamp = '';
    $end_time_stamp = '';
    if ($_POST['type'] == 1) {
        $start_time_stamp = strtotime($time.'00:00:00');
        $end_time_stamp = strtotime($time.'12:00:00');
        $result['msg'] = 1;
    }else
    {
        $start_time_stamp = strtotime($time.'12:00:00');
        $end_time_stamp = strtotime($time.'23:59:59');
        $result['msg'] = 2;
    }
    //用于显示的时间
    $start_time = date("Y-m-d H:i",$start_time_stamp);
    $end_time = date("Y-m-d H:i",$end_time_stamp);
    //订单数量
    $order_count = $GLOBALS['db']->getOne('SELECT COUNT(*) FROM '.$GLOBALS['ecs']->table('order_info').' WHERE ywid = "'.$user_id.'" AND add_time > '.$start_time_stamp.' AND add_time < '.$end_time_stamp);
    //初期现金
    $opening_cash = $GLOBALS['db']->getOne('SELECT balance FROM '.$GLOBALS['ecs']->table('cash_drawer').' WHERE user_id = '.$user_id.' AND add_time < '.$start_time_stamp.' ORDER BY add_time DESC ');
    //结束现金
    $end_cash = $GLOBALS['db']->getOne('SELECT balance FROM '.$GLOBALS['ecs']->table('cash_drawer').' WHERE user_id = '.$user_id.' AND add_time < '.$end_time_stamp.' ORDER BY add_time DESC ');
    //其他出入
    $other_in_out_transation = $end_cash - $opening_cash;
    //订单总额
    $order_amount = $GLOBALS['db']->getOne('SELECT SUM(order_amount) FROM '.$GLOBALS['ecs']->table('order_info').' WHERE ywid = '.$user_id.' AND add_time > '.$start_time_stamp.' AND add_time < '.$end_time_stamp.'');
    //余额总数
    $record_grand_total = $end_cash + $opening_cash; 
    //自定义订单数
    $other_order_count = 0;
    //折扣总数
    $total_discount = 0;
    //税总数
    $total_tax = 0;
    //所有总计加税
    $total_money = $other_in_out_transation + $total_tax;

    $smarty->assign('cashier',$cashier);
    $smarty->assign('start_time',$start_time);
    $smarty->assign('end_time',$end_time);
    $smarty->assign('order_count',$order_count);
    $smarty->assign('opening_cash',$opening_cash);
    $smarty->assign('other_in_out_transation',$other_in_out_transation);
    $smarty->assign('order_amount',$order_amount);
    $smarty->assign('record_grand_total',$record_grand_total);
    $smarty->assign('other_order_count',$other_order_count);
    $smarty->assign('total_discount',$total_discount);
    $smarty->assign('total_tax',$total_tax);
    $smarty->assign('total_money',$total_money);

    if ($result['msg'] == 1) {
        $result['content'] = $smarty->fetch('library/op2_div.lbi');
    }else
    {
        $result['content'] = $smarty->fetch('library/op3_div.lbi');
    }
    die(json_encode($result));
}

//获取日订单数据 
if ($act == 'get_end_report') {
    include_once('includes/cls_json.php');
    $json = new JSON;
    $result = array(
        'content'=>'',
        'msg'=>''
        );
    $user_id  = $_SESSION['user_id'];
    $time = date("Y-m-d",time());
    $start_time_stamp = strtotime($time.'00:00:00');
    $end_time_stamp = strtotime($time.'23:59:59');
    $order_list = $GLOBALS['db']->getAll(' SELECT * FROM '.$GLOBALS['ecs']->table('order_info').' WHERE ywid = '.$user_id.' AND add_time > '.$start_time_stamp.' AND add_time < '.$end_time_stamp.'');
    if ($order_list) {
        foreach ($order_list as $key => $value) {
            $order_list[$key]['cashier'] = $GLOBALS['db']->getOne(' SELECT user_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$value['ywid'].'"');
            $order_list[$key]['add_date'] = date("Y-m-d H:i:s",$value['add_time']);
            $order_list[$key]['customer'] = $GLOBALS['db']->getOne(' SELECT user_name FROM '.$GLOBALS['ecs']->table('users').' WHERE user_id = "'.$value['user_id'].'"');
        }
        $smarty->assign('order_list',$order_list);
    }
    $result['content'] = $smarty->fetch('library/op4_div.lbi');
    die(json_encode($result));
}

//最近添加的商品
if ($act == 'recently_add') {
    $user_id = $_SESSION['user_id'];
    $sql = 'SELECT goods_id FROM '.$GLOBALS['ecs']->table('goods').' WHERE is_new = 1 AND goods_number > 0';
    $result = $GLOBALS['db']->getAll($sql);

    $goods_list = array();
    foreach ($result as $k => $v) {
        if ($v['goods_id']) {
            $goods = $GLOBALS['db']->getRow('SELECT * FROM '.$GLOBALS['ecs']->table('goods').' WHERE goods_id = "'.$v['goods_id'].'"');
            $properties = get_goods_properties($v['goods_id']);
            $goods['specification'] = $properties['spe'];
            $goods['num'] = count($properties['spe']);
            array_push($goods_list, $goods);
        }
    }
    $smarty->assign('goods',              $goods_list);
    $record_count  = count($goods_list);
    $zongpage = ceil($record_count/16);
    $smarty->assign('zongpage',$zongpage);

    $result['content'] = $smarty->fetch('library/search_list.lbi');
    echo json_encode($result);exit;
}
//经常添加的16个商品
if ($act == 'frequently_add') {
    $sql = 'SELECT g.goods_id ' .
           'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g, ' .
                $GLOBALS['ecs']->table('order_info') . ' AS o, ' .
                $GLOBALS['ecs']->table('order_goods') . ' AS og ' .
           "WHERE g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0  " ;
    //判断是否启用库存，库存数量是否大于0
    $sql .= " AND g.goods_number > 0 ";
    $sql .= ' AND og.order_id = o.order_id AND og.goods_id = g.goods_id ' .
           "AND (o.order_status = '" . OS_CONFIRMED .  "' OR o.order_status = '" . OS_SPLITED . "') " .
           "AND (o.pay_status = '" . PS_PAYED . "' OR o.pay_status = '" . PS_PAYING . "') " .
           "AND (o.shipping_status = '" . SS_SHIPPED . "' OR o.shipping_status = '" . SS_RECEIVED . "') " .
           'GROUP BY g.goods_id ORDER BY g.goods_number DESC, g.goods_id DESC LIMIT ' . $GLOBALS['_CFG']['top_number'];
    $result = $GLOBALS['db']->getAll($sql);

    $goods_list = array();
    foreach ($result as $k => $v) {
        if ($v['goods_id']) {
            $goods = $GLOBALS['db']->getRow('SELECT * FROM '.$GLOBALS['ecs']->table('goods').' WHERE goods_id = "'.$v['goods_id'].'"');
            $properties = get_goods_properties($v['goods_id']);
            $goods['specification'] = $properties['spe'];
            $goods['num'] = count($properties['spe']);
            array_push($goods_list, $goods);
        }
    }
    $smarty->assign('goods',              $goods_list);
    $record_count  = count($goods_list);
    $zongpage = ceil($record_count/16);
    $smarty->assign('zongpage',$zongpage);

    $result['content'] = $smarty->fetch('library/search_list.lbi');
    echo json_encode($result);exit;
}

//客制化商品
if ($act == 'customer_cart') {
    include_once('includes/cls_json.php');
    $goods_name = empty($_POST['goodsName'])? '自定义商品' : trim($_POST['goodsName']);
    $goods_price = $_POST['goodsPrice'] ?   intval($_POST['goodsPrice']) : 0;
    $tax_type = $_POST['taxType'];
    $qty = $_POST['qty'] ? intval($_POST['qty']) : 1;
    $is_shipping = empty($_POST['isShipping'])? $_POST['isShipping'] : 0;

    $json = new JSON;
    $result = array(
        'goods_name'=>'',
        );
    //虚构商品加入购物车
    customer_cart_add($goods_name,$goods_price,$tax_type,$qty,$is_shipping);
    //获取购物车内的商品
    $cartgoods = get_cart_goods();

    $smarty->assign('cartgoods',              $cartgoods['goods_list']);
    $smarty->assign('zongji',              $cartgoods['total']);
    $sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id']."";
    $cnum = $db->getOne($sql);
    $result['zongji'] = $cartgoods['total']['goods_amount'];
    $smarty->assign('result',              $result);
    $result['content'] = $smarty->fetch('library/total-right.lbi');
    die(json_encode($result));
}

//客制化商品
if ($act == 'customer_edit_cart') {
    include_once('includes/cls_json.php');
    $goods_price = $_POST['goods_id'] ?   $_POST['goods_id'] : 0;
    $qty = $_POST['qty'] ? intval($_POST['qty']) : 1;
 

    $json = new JSON;
    $result = array(
        'content'=>'',
        );

    //获取购物车内的商品
    $cartgoods = get_cart_goods();

    $smarty->assign('cartgoods',              $cartgoods['goods_list']);
    $smarty->assign('zongji',              $cartgoods['total']);
    $sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id']."";
    $cnum = $db->getOne($sql);
    $result['zongji'] = $cartgoods['total']['goods_amount'];
    $smarty->assign('result',              $result);
    $result['content'] = $smarty->fetch('library/total-right.lbi');
    die(json_encode($result));
}
//客制化商品购物车修改数量 
if ($act == 'customer_update_cart') {
    include_once('includes/cls_json.php');
    $type = $_POST['type'];
    $session_id = SESS_ID;
    $goods_number = $GLOBALS['db']->getOne('SELECT goods_number FROM '.$GLOBALS['ecs']->table('cart').' WHERE session_id = "'.$session_id.'" AND goods_id = 0');
    if ($type) {
        $goods_number++;
    }else{
        $goods_number--;
    }
    $GLOBALS['db']->query(' UPDATE '.$GLOBALS['ecs']->table('cart').' SET goods_number = '.$goods_number.' WHERE session_id = "'.$session_id.'" AND goods_id = 0');

    $json = new JSON;
    $result = array(
        'content'=>'',
        );

    //获取购物车内的商品
    $cartgoods = get_cart_goods();

    $smarty->assign('cartgoods',              $cartgoods['goods_list']);
    $smarty->assign('zongji',              $cartgoods['total']);
    $sql = "select count(*) from " .$ecs ->table('cart')." where user_id=".$_SESSION['user_id']."";
    $cnum = $db->getOne($sql);
    $result['zongji'] = $cartgoods['total']['goods_amount'];
    $smarty->assign('result',              $result);
    $result['content'] = $smarty->fetch('library/total-right.lbi');
    die(json_encode($result));
}

//csv导出方法
function export_csv($filename,$data)   
{   
    header("Content-type:text/csv");   
    header("Content-Disposition:attachment;filename=".$filename);   
    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');   
    header('Expires:0');   
    header('Pragma:public');   
    echo $data;   
} 
?>
